package com.liu.activiti.filter;

import com.liu.activiti.handler.MyUserDetailsService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
@AllArgsConstructor
public class TokenFilter extends OncePerRequestFilter {

    private final MyUserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        filterChain.doFilter(request, response);

        /*if (request.getRequestURI().equals("/login")) {
            filterChain.doFilter(request, response);
            return;
        }


        log.info("开始验证用户token ... ");
        log.info("请求url = {} , method = {}, param = {}", request.getRequestURL(), request.getMethod(), request.getParameterMap());
        try {
            String token = request.getHeader(HttpHeaders.AUTHORIZATION);
            if (token != null && token.startsWith("Bearer ")) {

                token = token.substring(7); // 提取 Token
                String usernameFromToken = "";
                try {
                    usernameFromToken = JwtUtil.getUsernameFromToken(token);
                } catch (Exception e) {
                    throw new CustomException(HttpStateEnum.TOKENERROR.getMessages(), HttpStateEnum.TOKENERROR.getCode());
                }
                // 验证 Token 并设置安全上下文
                if (usernameFromToken != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                    UserDetails userDetails = userDetailsService.loadUserByUsername(usernameFromToken);

                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    // 设置 Spring Security 上下文
                    SecurityContextHolder.getContext().setAuthentication(authentication);

                }
            } else {
                throw new CustomException("token 为空或不符合标准！", HttpStateEnum.TOKENERROR.getCode());
            }
        } catch (CustomException exception) {
            ResponseUtils.endResponse(response, exception);
            return;
        }
        filterChain.doFilter(request, response);*/

    }


}
